<script setup lang="ts">
import { useList } from '@/composables/list-composable'
import { permListApi } from '@/api/perm'
import type { ResultData } from '@/api/service'
import type { Page } from '@/type/User'
import type { PermVo } from '@/type/system/perm-types'
import SList from '@/components/common/list/SList.vue'
import { ref } from 'vue'
import { rolePermListApi, saveRolePermApi } from '@/api/role-api'
import { ElNotification } from 'element-plus'

const props = defineProps<{
  roleId: string
  close: () => void
}>()

// 权限列表视图
const viewId = 'PermList'
// 定义列表的组合式函数
const { tableData, pageQuery, statement, total, tableLoading, search } = useList<PermVo>(
  viewId,
  getData,
  init
)

// s-list 列表引用
const sListRef = ref()
// 已拥有的权限列表
const defaultCheckedIds = ref<Set<string>>(new Set())

// 初始化已选中权限列表
async function init() {
  if (props.roleId !== undefined) {
    tableLoading.value = true
    try {
      const res = await rolePermListApi(props.roleId)
      defaultCheckedIds.value = new Set(res.data)
    } finally {
      tableLoading.value = false
    }
  }
}
// 查询权限列表
function getData() {
  tableLoading.value = true
  permListApi(pageQuery).then((response: ResultData<Page<PermVo[]>>) => {
    total.value = response.data.total
    tableData.value = response.data.modelList
    checkDefault()
    tableLoading.value = false
  })
}

// 默认选中已拥有权限列表
function checkDefault() {
  const checked = tableData.value.filter((td: PermVo) => defaultCheckedIds.value.has(td.permId));
  if (checked.length == 0) {
    return;
  }
  checked.map(it => it.permId).forEach((it) => defaultCheckedIds.value.delete(it))
  sListRef.value.toggleSelection(
    checked,
    true
  )
}

// 保存角色拥有权限
function saveRolePremList() {
  const selection = sListRef.value.selection as PermVo[]
  const params = selection.map((it) => it.permId)
  defaultCheckedIds.value.forEach((it) => params.push(it))
  saveRolePermApi(props.roleId, params).then(() => {
    ElNotification.success({
      title: '成功',
      message: '保存角色权限成功',
      type: 'success'
    })
    props.close()
  })
}
</script>

<template>
  <s-list
    ref="sListRef"
    :statement="statement"
    :data="tableData"
    :total="total"
    :table-loading="tableLoading"
    :page-size="pageQuery.pageSize"
    @search="search"
    :is-selection="true"
    row-key="permId"
    :row-button-show="false"
    :top-button-show="false"
  >
    <template #button-top-append-prev>
      <el-button type="primary" @click="saveRolePremList">保存</el-button>
    </template>
  </s-list>
</template>

<style scoped></style>
